<template>
    <div class="product-order">
        <div class="people-select text-normal">
            <div>是否到店自取</div>
            <div class="grey-text-color">
                <ZbSelect v-model="needAddress" type="small" :options="pickupOptions" :hasBr="true" default-br="#bbbbbb" default-color="#101010" selected-color="#F13C50" selected-br="#F13C50" selected-bg="#FEEDEF" />
            </div>
        </div>
        <!-- 地址信息 -->
        <ListinfoItemAddress v-if="!addressId && needAddress" label="收货地址" text="请填写" @click="onClickAddress" />
        <AddressItem v-if="addressId && needAddress"
            :name="address.name"
            :mobile="address.mobile"
            :address="address.province + address.city + address.district + address.detail"
            :tag="address.title"
            :is-default="address.is_default"
            action="修改地址"
            @action="onAction(address)"
            @click="onClickAddress(address)" />
        <div v-if="!needAddress">
            <ZbInput v-model.trim="form.name" type="text" title="姓名：" after-line="true" :input-class="['right']" placeholder="请输入联系人"></ZbInput>
            <ZbInput v-model.trim="form.phone" type="number" title="联系方式：" after-line="true" :input-class="['right']" placeholder="请输入联系方式"></ZbInput>
        </div>
        <ReferrerSelect v-model="referrerKey" :can-change="canChangeReferrer" :shop-id="shopIds" @referrerChange="handleReferrerChange"></ReferrerSelect>
        <!-- 商品信息 -->
        <div v-if="productList.length > 0" class="separation"></div>
        <div v-if="productList.length > 0" class="product-list-wrap">
            <template v-for="(product, index) in productList">
                <ProductInfoBar :key="'1_' + index"
                    :cover="product.cover[0]"
                    :spec="product.spec"
                    :name="product.name"
                    :price="product.price"
                    :count="product.count > 1 ? product.count : null" />
                <!-- <ProductDiscount :key="'2_' + index" :showTitle="false" :productId="product.id" :price="product.price" /> -->
            </template>
        </div>
        <div class="section pay-type">
            <div class="type text-huge" @click="onClickPayType('all')" :class="{'active': payType === 'all'}">全款支付</div>
            <div class="type" v-if="prepayPrice && canSelectPrepay" @click="onClickPayType('book')" :class="{'active': payType === 'book'}">
                <span class="text-huge">定金支付</span>
                <span class="text-small">需先支付{{prepayPriceText}}元</span>
            </div>
        </div>

        <!-- 优惠 -->
        <div v-if="matchedDiscount" class="separation"></div>
        <!-- <ListInfoItem label="代金券选择" :text="selectedCoupon ? -discountValue : usableList.length + '张可用'" @click="onClickCoupon" /> -->
        <ListInfoItem v-if="matchedDiscount"
            label="优惠抵扣/折扣"
            :text="'-￥' + currency(matchedDiscount.total_abatement)"
            :showArrow="false" />

        <!--  -->
        <div class="separation"></div>
        <div style="background-color: #ffffff;">
            <div class="list-info-item clearfix coupon-select text-normal clearfix" :style="checked == true ? 'padding-bottom:6rpx': ''">
                <div class="fl" style="font-weight: bold;">使用充值支付</div>
                <div class="fr ">
                    <span>
                        <!-- <van-switch v-model="checked" :disabled="disabledState" @click="checkAwitch" active-color="#F32414" size="30rpx" @change="checkUseBalance" /> -->
                        <van-switch :value="checked" @input="onInput" :disabled="disabledState"  active-color="#F32414" size="32rpx" @click="checkAwitch" />
                    </span>
                </div>
            </div>
            <div class="pkgbanlanceBox_down" v-if="checked">
                <div class="balanceTips">请注意：选择充值余额支付时，将不会产生推荐分红或返利金额！</div>
                <div class="list-info-item clearfix coupon-select text-normal clearfix" style="padding:20rpx 30rpx;">
                    <div class="fl" style="font-weight: bold;">充值支付 <span style="font-size: 22rpx;">(余额：{{thisMallRechargeMoney}})</span> </div>
                    <div class="fr">
                        <span style="display:flex;">
                            <span style="line-height:45rpx;">-￥</span>
                            <input type="number textRight" :style="{width:inputWidth(showpaymentMoney)}" v-model="showpaymentMoney">
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <!--  -->

        <div v-if="detail" class="separation"></div>
        <div v-if="detail" class="section price-detail">
            <div class="title after-line text-normal font-bold">价格明细</div>
            <PriceInfoBar label="产品价格" :price="detail.price" />
            <div class="title before-line clearfix text-normal">
                <div class="fr">
                    <span class="text-small">小计&emsp;</span>
                    <span>¥{{totalPrice1 | currency}}</span>
                </div>
            </div>
        </div>

        <!-- 备注 -->
        <div class="separation"></div>
        <div class="product-order__remark">
            <div class="product-order__remark-title after-line narrow">添加备注</div>
            <textarea v-model.trim="form.remark"
                class="product-order__remark-text"
                placeholder="点击输入">
            </textarea>
            <div class="product-order__remark-hint">
                {{form.remark.length}}/100
            </div>
        </div>

        <!-- 底部内容 :isBalance="discount.balance.is_balance"   -->
        <OrderPriceBar :price="payPrice" :is-paying="false" :isBalance="0" @pay="onClickPay" />
        <!-- <OrderPriceBar :price="payPrice" :is-paying="false" :isBalance="discountNew?(discountNew.balance?(discountNew.balance.is_balance?discountNew.balance.is_balance:0):0):0" @pay="onClickPay" /> -->
        <!-- <OrderPriceBar :price="payPrice" :is-paying="false" :isBalance="discountNew?discountNew.balance.is_balance:0" @pay="onClickPay" /> -->

        <!-- 取消支付后弹窗 -->
        <van-dialog v-model="showCancelPopup"
            title="确认要离开收银台"
            message="你的订单在2小时内未支付将被取消，要重新支付本订单，请在“我的”菜单页面，“待付款”中找到该订单进行支付"
            show-cancel-button
            cancel-button-text="确认离开"
            confirm-button-text="继续支付"
            @confirm="onConfirmPay(orderId)"
            @cancel="onCancelPay(orderId,payType)">
        </van-dialog>
    </div>
</template>

<script lang="ts">
import { api } from '@/lib/api';
import {
    dateNow,
    dateParse,
    currency,
    wait,
} from '@/lib/utils';
import {
    EMPTY_LIST,
    ROUTE_NAME,
} from '@/lib/constant';
import store from '@/store';
import AddressItem from '@/features/order/addressItem.vue';
import ProductInfoBar from '@/features/product/infoBar.vue';
import OrderPriceBar from '@/features/order/priceBar.vue';
import ListInfoItem from '@/components/list/infoItem.vue';

import ListinfoItemAddress from '@/components/list/infoItemAddress.vue';

import PriceInfoBar from '@/features/order/priceInfoBar.vue';
import ReferrerSelect from '@/features/order/referrerSelect.vue';
import ZbSelect from '@/components/common/zbSelect.vue';
import ZbInput from '@/components/common/zbInput.vue';
import ProductDiscount from '@/module/product/components/discount.vue';
import { checkValidate, ValidateRule, checkMobile } from '@/lib/script/validate';
import { Component, Mixins, Vue, Watch } from 'vue-property-decorator';
import { ShowRdata } from '@/mixins/showRdata';

@Component({
    name: 'ProductOrder',
    components: {
        AddressItem,
        ProductInfoBar,
        OrderPriceBar,
        ListInfoItem,
        ListinfoItemAddress,
        PriceInfoBar,
        ReferrerSelect,
        ZbSelect,
        ZbInput,
        ProductDiscount,
    },
    methods: {
        currency,
    },
})
export default class ProductOrder extends Mixins(ShowRdata) {
    public referrerKey: any = '';
    public selectedReferrer: any = null;
    public peopleSelectOptionsVisible: any = false;
    public updateCoupon: any = true;
    public dateNow: any = dateNow();
    public orderId: number | null = null;
    // 推送订单的id
    public sendMsgOrderId: any = [];

    /** 是否自提 */
    public needAddress = false;
    /** 自提选项 */
    public pickupOptions: ValueText[] = [
        { text: '是', value: false },
        { text: '否', value: true },
    ];
    /** 取消支付后弹窗 */
    public showCancelPopup = false;
    public payType: any = 'all';
    public form = {
        name: '',
        phone: '',
        remark: '',
    };
    // 显示余额支付 1
     public discountNew: any = {
        full_reduction: [],
        discount: [],
        balance: {
            is_balance: 0,
            is_recharge: 0,
            recharge_money: 0
        }
     };

    // 计算input宽度
    public get inputWidth(){
        return function (value) {
            if (value == '' || value == 0) {
            return '130rpx'
            } else {
            return String(value).length * 0.55 + 'rem'
            }
        }
    }
    
    // 滑块选中状态
    public checked:any = false;
    // 滑块是否禁用
    // public disabledState:any = false;
    // 滑块点击方法
    public onInput(checked){
        if(this.shopBalance > 0){
            this.checked = checked;
        }else{
            this.checked == false;
            wx.showToast({
                title: '余额支付不足',
                icon: 'none',
            });
        }
    }
    // public checkUseBalance(e){
    //     this.checked = e;
    // }
    public checkAwitch(){
        if(this.disabledState == true){  // 商品不支持余额支付 is_balance == 0
            if(this.payType == 'all'){
                wx.showToast({
                    title: '该商品非充值余额支付商品',
                    icon: 'none',
                });
            }else{
                wx.showToast({
                    title: '不支持充值支付',
                    icon: 'none',
                });
            }
            
        }
    }
    //  监听开关状态
     @Watch('checked')
     public changeChecked(){
        if(this.checked == false){
            this.showpaymentMoney = 0;
        }else{
            this.showpaymentMoney = this.thisMallRechargeMoney;
        }
     }
     public get disabledState(){
         return (this.discountNew?(this.discountNew.balance?(this.discountNew.balance.is_balance?this.discountNew.balance.is_balance:0):0):0) == 1 && this.payType === 'all' ? false : true;
     }

    // 新增订单混合支付
    // 当前用户在门店中余额
    public thisMallRechargeMoney: any = 0;
    // 页面显示金额
    public showpaymentMoney: any = 0;

    @Watch('showpaymentMoney')
    public OnthisMallRechargeMoney() {
        if(this.checked == false){
            this.showpaymentMoney = 0;
        }else{
            // 商品金额 小于 当前门店金额 = 显示当前商品金额
            if (this.totalPrice1 <= this.showpaymentMoney * 100) {
                // 返回商品金额减去门店金额 = 所需支付的金额
                this.showpaymentMoney = this.totalPrice1/100;
                return;
            }
            // 支付方式 全款支付 只操作全款支付
            // this.payType === 'book' ? this.prepayPrice : this.totalPrice1
            let newMoney = this.showpaymentMoney; // 支付金额
            if(this.payType === 'all' && (this.discountNew?this.discountNew.balance.is_balance:0)){
                // 修改金额 小于 需支付金额
                if(newMoney*100 > this.thisMallRechargeMoney * 100){
                    wx.showToast({
                        title: '账户余额不足',
                        icon: 'none',
                    });
                    this.showpaymentMoney = this.thisMallRechargeMoney;
                    return;
                }
                if(newMoney*100 > this.totalPrice1){
                    wx.showToast({
                        title: '修改的金额不能大于支付金额',
                        icon: 'none',
                    });
                    this.showpaymentMoney = this.totalPrice1/100;
                    return;
                }
                // 修改金额 大于 0
                if(newMoney*100 < 0){
                    wx.showToast({
                        title: '金额不能大于订单金额',
                        icon: 'none',
                    });
                    this.showpaymentMoney = 0;
                    return;
                }
            }
        }
        
    }

    public canChangeReferrer: any = true;
    // debounceGetReferrerList: null,
    // 获取会员在个店铺中的余额
    public get getshopBalance(){
        return store.state.user.shopBnlance;
    }
    public get shopBalance(){
        let balance = 0;
        for(var i=0;i< this.getshopBalance.length;i++){
            if(this.getshopBalance[i].shop_id == this.shopdetail){
                balance = this.getshopBalance[i].balance;
            }
        }
        return balance;
    }
    /** 商品详情 */
    public get shopdetail() {
        return store.state.good.productDetailMap[this.shopId].shop_id;
    }


    public get shopId() {
        return this.$route.params.shopId;
    }
    public get referrerId() {
        return this.$route.query.referrer;
    }
    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }
    public get hasLogin() {
        return store.state.auth.hasLogin;
    }
    /** 购物车信息 */
    public get cartMap() {
        return store.state.shop.cart;
    }
    /** 商品详情 */
    public get productDetailMap() {
        return store.state.good.productDetailMap;
    }
    /** 规格信息 */
    public get spec() {
        return store.state.good.spec;
    }
    public get referrer() {
        return store.state.user.referrer;
    }
    public get bindReferrerId() {
        return store.state.user.bindReferrerId;
    }
    public get referrerList() {
        return store.state.user.referrerList;
    }
    /** 代金券列表 */
    public get couponList() {
        return store.state.user.couponList;
    }
    /** 代金券数据 */
    public get couponMap() {
        return store.state.user.couponMap;
    }
    // 所属店铺
    public get memberShopList() {
        return store.state.user.memberShopList;
    }
    /** 代金券id */
    public get couponId() {
        return store.state.order.couponId;
    }
    /** 地址id */
    public get orderAddressId() {
        return store.state.order.addressId;
    }
    /** 等待支付 */
    public get pendingCart() {
        return store.state.order.pendingCart;
    }
    /** 详情 */
    public get addressDetail() {
        return store.state.address.detail;
    }
    /** 默认地址 */
    public get defaultAddress() {
        return store.state.address.default;
    }
    // 所属店铺id
    public get memberShopIdList() {
        return this.memberShopList.map((item: any) => {
            return String(item.shop_id);
        });
    }
    /** 购物车信息 */
    public get cart() {
        return this.cartMap || {};
    }
    /** 商品列表 */
    public get productList() {
        const list = [];
        for (const key in this.pendingCart) {
            list.push(...this.pendingCart[key].map((item: any) => {
                const product = this.productDetailMap[item.product_id];
                const spec = this.spec[item.spec_id];

                // 处理规格多次显示
                let selectSpecParam = '';
                if(spec){
                    for(let i in spec.param){
                        if(i.indexOf('attr') != -1){
                            selectSpecParam = selectSpecParam + ' ' + spec.param[i];
                        }
                    }
                }

                if (!product || !spec) {
                    return;
                }
                return {
                    id: product.id,
                    shop_id: product.shop_id,
                    product_id: item.product_id,
                    cover: product.cover,
                    name: product.name,
                    price: spec.price,
                    prepay_price: spec.prepay_price,
                    spec: selectSpecParam,
                    // spec: Object.values(spec.param).join(' '),
                    count: item.count,
                };
            }).filter((_: any) => _));
        }
        return list;
    }
    public get productIds() {
        const list = [];
        for (const key in this.pendingCart) {
            list.push(...this.pendingCart[key].map((item: any) => String(item.product_id)));
        }
        return list;
        // return this.pendingCart.map(item => String(item.product_id));
    }
    public get shopIds() {
        return this.productList.map((item: any) => {
            return item.shop_id;
        });
    }
    public get canSelectPrepay() {
        return this.productIds.length === 1;
    }
    public get prepayPrice() {
        return this.canSelectPrepay && this.productList[0].prepay_price ? this.productList[0].prepay_price : 0;
    }
    public get prepayPriceText() {
        return currency(this.prepayPrice);
    }
    /** 列表 */
    public get wrap() {
        return this.couponList['useable'] || EMPTY_LIST;
    }
    /** 列表 */
    public get list() {
        return this.wrap.list.map((id: any) => this.couponMap[id]);
    }
    /** 可以使用的代金券 */
    public get usableList() {
        return this.list.filter((coupon: any) => {
            return this.checkCoupon(coupon);
        });
    }
    /** 最大最快到期的代金券 */
    public get maxUsableCoupon() {
        let resultCoupon = null;
        let resultDiscountValue = null;
        this.usableList.forEach((item: any) => {
            if (!resultCoupon) {
                resultCoupon = item;
                resultDiscountValue = this.getDiscountValue(item);
            } else {
                const tempDiscountValue = this.getDiscountValue(item);
                if (tempDiscountValue > resultDiscountValue) {
                    resultCoupon = item;
                    resultDiscountValue = tempDiscountValue;
                } else if (tempDiscountValue === resultDiscountValue) {
                    if (dateParse(resultCoupon.expiration_date).valueOf() > dateParse(item.expiration_date).valueOf()) {
                        resultCoupon = item;
                        resultDiscountValue = tempDiscountValue;
                    }
                }
            }
        });
        return resultCoupon;
    }
    public get selectedCoupon() {
        return this.couponId ? this.couponMap[this.couponId] : null;
    }
    /** 折扣金额 */
    public get discountValue() {
        if (!this.selectedCoupon) {
            return 0;
        }
        return currency(this.getDiscountValue(this.selectedCoupon));
    }
    public get shopPriceMap() {
        const map = {};
        for (const key in this.pendingCart) {
            let result = 0;
            for (const product of this.pendingCart[key]) {
                const price = this.spec[product.spec_id].price;
                result += price * product.count;
            }
            map[key] = result;
        }
        return map;
    }
    /** 总价格 */
    public get totalPrice() {
        let result = 0;
        for (const product of this.productList) {
            result += product.price * product.count;
        }
        return result;
    }
    /** 选中的优惠 */
    public get matchedDiscount() {
        if (this.productList.length > 1) {
            return;
        }
        const discount = store.state.good.discount[this.productIds[0]] || {
            full_reduction: [],
            discount: [],
            // 新增
            balance: {
                is_balance: 0,
                is_recharge: 0,
                recharge_money: 0
            }

        };
        let result: (Product.FullReductionDiscount & { total_abatement: number; }) | null = null;
        // 购物车多个商品不支持余额支付
        if(this.productList.length <= 1){
       
            // 存储当前门店余额
            this.thisMallRechargeMoney = this.shopBalance;
            // this.showpaymentMoney = this.shopBalance;
            this.discountNew = discount;

        }
            // let result: (Product.FullReductionDiscount & { total_abatement: number; }) | null = null;
            for (let item of discount.full_reduction || []) {
                if (this.totalPrice >= item.limit) {
                    if (!result) {
                        result = {
                            ...item,
                            total_abatement: item.abatement * Math.floor(this.totalPrice / item.limit),
                        };
                    } else {
                        const totalAbatement = item.abatement * Math.floor(this.totalPrice / item.limit);
                        if (totalAbatement > result.total_abatement) {
                            result = {
                                ...item,
                                total_abatement: totalAbatement,
                            };
                        }
                    }
                }
            }
            for (let item of (discount.discount || [])) {
                if (this.totalPrice >= item.limit) {
                    if (!result) {
                        result = {
                            id: item.id,
                            title: item.title,
                            limit: item.limit,
                            abatement: item.ratio,
                            total_abatement: (this.totalPrice / item.limit) * (100 - item.ratio),
                        };
                    } else {
                        const totalAbatement = (this.totalPrice / item.limit) * (100 - item.ratio);
                        if (totalAbatement > result.total_abatement) {
                            result = {
                                id: item.id,
                                title: item.title,
                                limit: item.limit,
                                abatement: item.ratio,
                                total_abatement: totalAbatement,
                            };
                        }
                    }
                }
            }
        
        return result;
    }
    /** 总价格 */
    public get totalPrice1() {
        if (this.totalPrice - Number(this.discountValue) * 100 > 0) {
            return this.totalPrice - Number(this.discountValue) * 100 - (this.matchedDiscount?.total_abatement || 0);
        }
        return 0;
    }
    /** 支付价格 */
    public get payPrice() {
        return this.payType === 'book' ? this.prepayPrice : (this.discountNew?(this.discountNew.balance?(this.discountNew.balance.is_balance?this.totalnewpayPrice:this.totalPrice1):this.totalPrice1):this.totalPrice1) ;
        // return this.payType === 'book' ? this.prepayPrice : this.totalPrice1;
    }
    /** 支付价格 */
    public get payPriceText() {
        return currency(this.payPrice);
    }
    /** 全款支付使用混合支付显示的支付价格 */
    public get totalnewpayPrice() {
        // 当前门店金额大于0
        if(this.showpaymentMoney > 0){
            // 如果支付金额大于当前门店金额，显示充值金额为商品金额
            if (this.totalPrice1 >= this.showpaymentMoney * 100) {
                // 返回商品金额减去门店金额 = 所需支付的金额
                return this.totalPrice1 - this.showpaymentMoney * 100;
            }else{
                return this.totalPrice1;
            }
        }else{
            return this.totalPrice1
        }

    }

    /** 地址id */
    public get addressId() {
        if (this.orderAddressId) {
            return this.orderAddressId;
        }
        if (this.defaultAddress) {
            return this.defaultAddress.id;
        }
        return null;
    }
    /** 地址信息 */
    public get address() {
        return this.addressDetail[this.addressId];
    }
    /** 检查规则 */
    public get rules(): { [key: string]: ValidateRule[] } {
        return {
            name: [
                { required: true, message: '请填写联系人' },
            ],
            phone: [
                { required: true, message: '请填写联系方式' },
                { fn: checkMobile, message: '请填写正确的手机号' },
            ],
        };
    }

    @Watch('form.remark')
    public onFormRemark() {
        const remark = this.form.remark;
        if (remark.length > 100) {
            this.form.remark = remark.slice(0, 100);
        }
    }

    /**
     * 点击编辑
     */
    public onAction(address: Address.ListItem) {

        api.push({
            name: ROUTE_NAME.ADDRESS_ADD,
            query: {
                addressId: address.id + '',
            },
        });
    }
    /**
     * 点击地址
     */
    public onClickAddress() {
        api.push({
            name: ROUTE_NAME.ADDRESS_LIST,
            query: {
                enableSelect: '1',
            },
        });
    }

    /**
     * 计算折扣金额
     */
    public getDiscountValue(coupon: any) {
        const number = Number(coupon.money);
        return number;
    }

    public onClickPayType(type: any) {
        this.payType = type;
        if(this.payType == 'book'){
            this.checked = false;
        }
    }

    /**
     * 检查是否可用代金券
     */
    public checkCoupon(coupon: any) {
        const matchGood = !coupon.applicable ? true : coupon.applicable.some((item: any) => this.productIds.includes(String(item)));
        let matchShopPrice = true;
        if (coupon.shop_id) {
            if (this.shopPriceMap[coupon.shop_id]) {
                matchShopPrice = Number(coupon.price_limit) <= this.shopPriceMap[coupon.shop_id];
            } else {
                matchShopPrice = false;
            }
        } else {
            matchShopPrice = Number(coupon.price_limit) <= Number(this.totalPrice);
        }
        // const matchPrice = Number(coupon.price_limit) <= Number(this.totalPrice);
        const matchTime = this.dateNow.valueOf() <= dateParse(coupon.expiration_date).valueOf();
        const matchType = !coupon.type ? true : (coupon.type === 'good');
        return matchGood && matchShopPrice && matchTime && matchType;
    }

    public handleReferrerChange(referrer: any) {
        this.selectedReferrer = referrer;
    }

    /**
     * 点击代金券
     */
    public onClickCoupon() {
        // api.navigateTo({
        //     url: '/pages/coupon_select/main',
        //     query: {
        //         is_select: 1,
        //         price: this.totalPrice,
        //         type: 'good',
        //     },
        // });

        api.push({
            name: ROUTE_NAME.MALL_COUPON_SELECT,
            query: {
                isSelect: '1',
                price: this.totalPrice + '',
                type: 'good',
            },
        });
    }

    /**
     * 创建订单
     */
    public async onClickPay(_type) {
        // let ispayType = 0;
        // if(_type == 'balance' || this.totalnewpayPrice == 0){
        //     ispayType = 1
        // }else{
        //     ispayType = 0
        // }

        if (!this.addressId && this.needAddress) {
            wx.showToast({
                title: '请选择地址',
                icon: 'none',
            });
            return;
        }
        if (!this.needAddress) {
            const keys = Object.keys(this.rules);
            for (const key of keys) {
                const fail = checkValidate(this.form[key], this.rules[key]);
                if (fail) {
                    wx.showToast({
                        title: fail.message,
                        icon: 'none',
                    });
                    return;
                }
            }
        }

        // 创建订单
        store.commit('utils/startRequest');
        const address = this.address;
        const tempCart = JSON.parse(JSON.stringify(this.pendingCart));
        for (const key in tempCart) {
            tempCart[key] = tempCart[key].map((item: any) => ({ id: item.spec_id, number: item.count }));
        }
        // 进入订单支付
        const payRes = await store.dispatch('order/createProductOrder', {
            goods_id: this.shopId,
            spec: tempCart,
            referrerId: this.selectedReferrer ? this.selectedReferrer.id : null,
            couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
            name: !this.needAddress ? this.form.name : address.name,
            mobile: !this.needAddress ? this.form.phone : address.mobile,
            address: !this.needAddress ? null : [ address.province, address.city, address.district, address.detail ].join(''),
            delivery: !this.needAddress ? 0 : 1,
            isPrepay: this.payType === 'book' ? 1 : 0,
            remark: this.form.remark,
            hasDiscount: !!this.matchedDiscount,
            // payType: ispayType,
            payType:  this.payType == 'all'? (this.showpaymentMoney > 0? 1 : 0) : 0,
            balance_pay: this.payType == 'all'? this.showpaymentMoney* 100 : 0,
        });
        if (payRes.statusCode !== 200 || payRes.data.status !== 0) {
            store.commit('utils/endRequest');
            wx.showToast({
                title: payRes.data.message,
                icon: 'none',
            });
            return;
        }
        // 找到相同的商品删除
        for (const key in this.pendingCart) {
            for (const item of this.pendingCart[key]) {
                if (this.cart[key]) {
                    this.cart[key] = this.cart[key].filter((tempItem: any) => {
                        return tempItem.product_id !== item.product_id;
                    });
                }
            }
        }
        await store.dispatch('shop/updateCart', {
            cart: this.cart,
        });
        const orderId = this.orderId = payRes.data.data.id;
        const params = payRes.data.data.params;
        this.sendMsgOrderId = payRes.data.data.order_id;
        this.updateCoupon = true;

        if (!params) {
            store.commit('utils/endRequest');
            api.push({
                name: ROUTE_NAME.ORDER_RESULT,
                params: {
                    type: 'product',
                    orderId,
                },
            });
            return;
        }
        store.commit('utils/endRequest');
        // 余额支付
        if(_type == 'balance' || this.totalnewpayPrice == 0){
            wx.showToast({
                title: '购买成功',
                icon: 'success',
            });
            setTimeout(() => {
                api.push({
                    name: ROUTE_NAME.ORDER_RESULT,
                    params: {
                        type: 'product',
                        orderId: orderId + '',
                    },
                });
            }, 1000);
        }else{
            // 微信支付
            this.onConfirmPay(orderId,params);
        }

        // this.onConfirmPay(orderId, params);
    }
    /**
     * 取消支付
     */
    public onCancelPay(orderId,payType) {
        for(var i=0;i<this.sendMsgOrderId.length;i++){
            store.dispatch('order/checkBackSendMsg', {
                orderId:this.sendMsgOrderId[i],
                type: 'shop',
                pickType:this.needAddress,
                payType: payType,
                forceUpdate: true,
            });
        }

        // store.dispatch('order/checkBackSendMsg', {
        //     orderId:orderId,
        //     type: 'shop',
        //     pickType:this.needAddress,
        //     payType: payType,
        //     forceUpdate: true,
        // });
        api.push({
            name: ROUTE_NAME.ORDER_LIST,
            query: {
                status: 'init',
            },
        });
    }
    /**
     * 确认支付
     */
    public async onConfirmPay(orderId: number, params?: any) {
        if (!params) {
            store.commit('utils/startRequest');
            const res = await store.dispatch('order/pay', {
                orderId,
            });
            store.commit('utils/endRequest');

            this.showRdata(res.data, '', () => {
                params = res.data.data;
            });
        }

        const result = await api.requestPayment({
            ...params,
            timeStamp: params.timestamp,
        }).catch((err: any) => {
            return err;
        });

        store.commit('utils/startRequest');
        if (result && result.errMsg.indexOf('requestPayment:ok') >= 0) {
            // 轮询
            let success = false;
            for (let i = 0; i < 20; i++) {
                const res = await store.dispatch('order/getPayStatus', {
                    id: orderId,
                    type: 'product',
                });
                if (res.statusCode !== 200 || res.data.status !== 0) {
                    wx.showToast({
                        title: '发生了一些错误',
                        icon: 'none',
                    });
                    break;
                } else if (res.data.data !== 'init') {
                    success = true;
                    break;
                } else {
                    await wait(1000);
                }
            }

            if (success) {
                wx.showToast({
                    title: '购买成功',
                    icon: 'success',
                });
                setTimeout(() => {
                    api.push({
                        name: ROUTE_NAME.ORDER_RESULT,
                        params: {
                            type: 'product',
                            orderId: orderId + '',
                        },
                    });
                }, 1000);
            }
        } else {
            if (result.errMsg.indexOf('requestPayment:fail cancel') >= 0) {
                store.dispatch('order/getList', {
                    status: 'init',
                    offset: 0,
                    count: 10,
                    forceUpdate: true,
                });
                this.showCancelPopup = true;
            }
        }
        store.commit('utils/endRequest');
    }

    public async created() {
        this.referrerKey = '暂无推荐人邀请';
        this.selectedReferrer = null;
        this.updateCoupon = true;
        this.payType = 'all';
        this.canChangeReferrer = true;
        const list: string[] = [];
        for (const key in this.pendingCart) {
            list.push(...this.pendingCart[key].map((item) => String(item.product_id)));
        }
        store.commit('utils/startRequest');
        await Promise.all([
            store.dispatch('address/getDefault'),
            store.dispatch('user/getReferrerInfo'),
            store.dispatch('user/getMemberShopList'),

            store.dispatch('user/getShopBanlance'),
            // store.dispatch('user/getReferrerList', {
            //     name: this.referrerKey,
            // }),
            ...list.map((item) => {
                return store.dispatch('good/getDetail', {
                    productId: item,
                });
            }),
            // wenti
            ...list.map((item) => {
                return store.dispatch('good/getDiscount', {
                    goodId: item,
                    referrer: this.referrerId,
                });
            }),
        ]);

        if (this.bindReferrerId) {
            const referrerRdata = await store.dispatch('user/checkReferrer', {
                shopId: this.shopIds,
                userId: this.bindReferrerId,
            });
            if (referrerRdata.status === 0 && referrerRdata.data) {
                this.selectedReferrer = referrerRdata.data;
                this.referrerKey = this.selectedReferrer.name || this.selectedReferrer.nickname;
                this.canChangeReferrer = false;
            }
        } else {
            // 返利会员自己所属店铺 商家职员和城市合伙人下单返利为自己
            // 返利会员自身是否合法
            let checkSelfShop = true;
            for (const item of this.shopIds) {
                if (!this.memberShopIdList.includes(String(item))) {
                    checkSelfShop = false;
                    break;
                }
            }
            if (checkSelfShop || this.userBasicInfo.level > 1) {
                this.selectedReferrer = this.userBasicInfo;
                this.referrerKey = this.selectedReferrer.name || this.selectedReferrer.nickname;
            }
            // else if (this.referrer) {
            //     this.selectedReferrer = this.referrer;
            //     this.referrerKey = this.referrer.name || this.referrer.nickname;
            // }
        }
        store.commit('utils/endRequest');
    }
    public async mounted() {
        if (this.updateCoupon) {
            /** 假设设置的全部代金券，需要在某个地方获取所有可用代金券 */
            await store.dispatch('user/getCouponList', {
                status: 'useable',
                offset: 0,
                count: 100,
            });
            const coupon = this.maxUsableCoupon;
            store.commit('order/setCouponId', coupon ? coupon.id : null);
            this.updateCoupon = false;
        }
    }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.balanceTips{
    width: 100%;
    padding: 0rpx 4% 15rpx 4%;
    color: #BDBDBD;
    font-size: 22rpx;
    box-sizing: border-box;
}
.red-text-color{
    color: red;
}
.textRight{
    text-align: right;
}
.product-order {
    padding-bottom: 50px + 10px;

    .product-list-wrap {
        padding: 15rpx 0;
    }
    .price-detail {
        padding: 0 17px;
        .title {
            position: relative;
            padding: 11px 0;
        }
    }
    .people-select {
        position: relative;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 5px 30rpx;
        .picker-box {
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;
            align-items: center;
            min-width: 90px;
            padding: 5px 10px;;
            border: 1px solid #BBBBBB;
            border-radius: 5px;
        }
        .date-picker {
            width: 224px;
            height: 24px;
            padding: 5px 16rpx;
            .picker {
                flex: 1;
            }
        }
    }
    .pay-type {
        display: flex;
        justify-content: space-around;
        padding: 15px 0rpx;
        .type {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            width: 152px;
            height: 53px;
            border-radius: 14rpx;
            border: 1px solid #bbb;
            background-color: #f5f5f5;
            &.active {
                color: #F13C50;
                border: 1px solid #F13C50;
                background-color: rgba(241, 60, 80, 0.09);
            }
        }
    }

    &__remark {
        background-color: @color-white;
        &-title {
            position: relative;
            padding: 10px 15px;
            .text-normal();
            .font-semi();
        }
        &-text {
            width: 100%;
            height: 90px;
            padding: 10px 15px;
            .text-normal();
            box-sizing: border-box;
        }
        &-hint {
            padding: 0 15px 10px;
            .text-small();
            color: @color-font-3;
            text-align: right;
        }
    }

    &__discount {
        padding: 12px 15px;
        &-value {
            float: right;
            color: @color-red;
        }
    }
}

</style>
